package jwt

import (
	"boy-go/pkg/config"
	"fmt"
	"github.com/golang-jwt/jwt/v5"
	"time"
)

var jwtSecret = []byte("asdasdasdwqeqeqwdqwe1") // 密钥，请替换为更安全的值
var expireTime = 30

type Claims struct {
	jwt.RegisteredClaims
	Uuid     string `json:"uuid"`
	Username string `json:"username"`
}

func InitJWT(conf config.TokenConfig) {
	jwtSecret = []byte(conf.Secret)
	expireTime = conf.ExpireTime
}

func GenerateToken(uuid string, username string) (*string, error) {
	expirationTime := time.Now().Add(time.Duration(expireTime) * time.Minute)
	claims := &Claims{
		Uuid:     uuid,
		Username: username,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(expirationTime),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			Issuer:    "boy-go",
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS512, claims)
	if token == nil {
		return nil, fmt.Errorf("token is nil")
	}
	t, err := token.SignedString(jwtSecret)
	return &t, err
}
func ParseToken(tokenStr string) (*Claims, error) {
	claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (interface{}, error) {
		return jwtSecret, nil
	})
	if err != nil {
		return nil, err
	}
	if !token.Valid {
		return nil, jwt.ErrTokenInvalidClaims
	}
	return claims, nil
}
